package GoodsLimitService

import (
	"context"
	"errors"
	"fmt"
	"gdshop-font-api-go/app/entity"
	"gdshop-font-api-go/app/response/AddressResp"
	"gdshop-font-api-go/app/response/OrderResp"
	toolsDb "gdshop-font-api-go/library/tools/db"
	"github.com/gogf/gf/encoding/gjson"
	"github.com/gogf/gf/util/gconv"
	"github.com/syyongx/php2go"
	"strings"
)

func CheckAddressLimit(ctx context.Context, orderItems []*OrderResp.OrderItem, addressModel *AddressResp.Item) error {
	tmp := strings.Split(addressModel.AddressCode, "")
	if len(tmp) < 6 {
		return errors.New("address_code 地址信息错误")
	}
	// 先处理全部商品选项
	var glList []*entity.GoodsLimit
	err := toolsDb.GetUnSafaTableAddDeleteWhere(ctx, "goods_limit").Where(
		"limit_type = 1 AND is_all_goods = 1 AND status = 1 " +
			"AND start_time <= unix_timestamp(now()) AND end_time >= unix_timestamp(now())").Structs(&glList)
	if err != nil {
		return err
	}
	// 循环取出每个商品ID
	goodsIds := []int{}
	goodsId := 0
	for _, o := range orderItems {
		for _, g := range o.Goodss {
			goodsId = gconv.Int(g.Id)
			if !php2go.InArray(goodsId, goodsIds) {
				goodsIds = append(goodsIds, goodsId)
			}
		}
	}

	for _, gl := range glList {
		err := checkByOneGoodsLimit(gl, tmp)
		if err != nil {
			return err
		}
	}

	// 判断 非全部商品选项时的地址禁售
	err = toolsDb.GetUnSafaTableAddDeleteWhere(ctx, "goods_limit").Where(
		"limit_type = 1 AND is_all_goods = 0 AND status = 1 " +
			"AND start_time <= unix_timestamp(now()) AND end_time >= unix_timestamp(now())").Structs(&glList)
	if err != nil {
		return err
	}
	for _, gl := range glList {
		// 取出限制里面的商品ID
		fmt.Println("glgl", gl.Name)
	}

	return nil
}

func checkByOneGoodsLimit(gl *entity.GoodsLimit, addressCodes []string) error {
	if len(addressCodes) < 6 {
		return errors.New("address_code 地址信息错误")
	}
	lr, err := gjson.LoadContent(gl.LimitRules)
	if err != nil {
		return err
	}
	lrArr := lr.GetStrings(".")
	for _, s := range lrArr {
		switch len(s) {
		case 2:

			if s == (addressCodes[0] + addressCodes[1]) {
				return errors.New("当前省份禁售")
			}
			break
		case 4:
			if s == (addressCodes[0] + addressCodes[1] + addressCodes[2] + addressCodes[3]) {
				return errors.New("当前城市禁售")
			}
			break
		case 6:
			if s == (addressCodes[0] + addressCodes[1] + addressCodes[2] + addressCodes[3] + addressCodes[4] + addressCodes[5]) {
				return errors.New("当前地区禁售")
			}
			break
		}
	}

	return nil
}
